package org.anderes.playground.csv;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class CsvFileHandler {

	private final File csvFile;
	
	private CsvFileHandler(final File csvFile) {
		this.csvFile = csvFile;
	}

	public static CsvFileHandler build(final File csvFile) {
		if (csvFile == null) {
			throw new IllegalArgumentException("Der Parameter 'csvFile' ist null");
		}
		return new CsvFileHandler(csvFile);
	}

	/**
	 * Schreibt die Map als CSV-File inkl. Header
	 * @param map Map mit Informationen
	 * @throws Exception Wenn ein Fehler beim Schreiben auftritt
	 */
	public void writeMap(final Map<String, String> map) throws Exception {
		if (map == null) {
			throw new IllegalArgumentException("Der Parameter 'map' ist null");
		}
		
		// CSV-File im UTF-8 mit BOM, damit allfällige Umlaute im Excel richtig dargestellt werden.
		PrintWriter writer = new PrintWriter(csvFile, "UTF-8");
		writer.print('\uFEFF'); // BOM
		
		// Header-Informationen schreiben
		writer.append("KEY").append(";").append("VALUE").append(System.getProperty("line.separator"));
		
		for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
			String key = iter.next();
			writer.append(key).append(";").append(map.get(key));
			if (iter.hasNext()) {
				writer.append(System.getProperty("line.separator"));
			}
		}
		
		writer.close();
	}

	public Map<String, String> readCsvFile() throws Exception {
		Map<String, String> map = new TreeMap<String, String>();
		LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(csvFile), "UTF-8"));
		String line = reader.readLine();
		while(line != null) {
			line = reader.readLine();
			if (line != null && line.matches("[^;]*[;][^;]*")) {
				String[] a = line.split(";");
				map.put(a[0], a[1]);
			}
		};
		return map;
	}

	
}
